//app.js
import TIM from "tim-wx-sdk";
import COS from "cos-wx-sdk-v5";
import GenerateTestUserSig from "./utils/GenerateTestUserSig.js";
//测试环境
// const SDKAppID = 1400294949;
//正式
const SDKAppID = 1400379977;


App({
  initTimSDK() {
    let that = this;
    let userId = "" + that.globalData.userInfo.id;
    let userSig = GenerateTestUserSig.genTestUserSig(userId).userSig;
    // 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
    let tim = TIM.create({
      SDKAppID: SDKAppID
    });

    // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
    // tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
    tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用

    // 注册 COS SDK 插件
    tim.registerPlugin({ "cos-wx-sdk": COS });
    tim
      .login({ userID: userId, userSig: userSig })
      .then(function(imResponse) {
        console.log("登录成功", imResponse.data); // 登录成功
        console.log("app.globalData.userInfo", that.globalData.userInfo);
      })
      .catch(function(imError) {
        console.warn("login error:", imError); // 登录失败的相关信息
      });
    tim.on(TIM.EVENT.SDK_READY, function(event) {
      // 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
      // event.name - TIM.EVENT.SDK_READY
      that.$tim = tim;
      that.isTimReady = true;
      that.$tim
        .updateMyProfile({
          nick: that.globalData.userInfo.nickname,
          avatar: that.globalData.userInfo.avatar
        })
        .then(function(_imResponse) {
          console.log("更新资料成功", _imResponse.data); //
        })
        .catch(function(imError) {
          console.warn("更新资料失败", imError); // 更新资料失败的相关信息
        });
    });
  },
  onLaunch: function() {
    let that = this;
    wx.getSetting({
      success(res) {
        let hasUserInfo = res.authSetting["scope.userInfo"];
        if (hasUserInfo) {
          that.globalData.userInfo = wx.getStorageSync("user_info");
          that.globalData.token = wx.getStorageSync("token");
          that.initTimSDK();
        }
      }
    });
  },
  globalData: {
    userInfo: null,
    token: wx.getStorageSync("token")
  },
  $tim: null,
  isTimReady: false
});
